<?php

namespace app\data\service;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\SDK\ViapiUtils\ViapiUtils;
use think\admin\Service;
use think\Exception;

/**
 * 阿里云服务
 * Class AliService
 * @package app\data\service
 */
class AliService extends Service
{
    /**
     * 识别驾驶证
     * @param $fileUrl
     * @param $side
     * @return array
     * @throws ClientException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recognizeDrivingLicense($fileUrl, $side = 'face')
    {
        $fileUrl = str_replace('https://', 'http://', $fileUrl);

        $accessKeyId = sysconf('storage.alioss_access_key');
        $accessKeySecret = sysconf('storage.alioss_secret_key');
        $fileLoadAddress = ViapiUtils::upload($accessKeyId, $accessKeySecret, $fileUrl);

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId('cn-shanghai')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('ocr')
                // ->scheme('https') // https | http
                ->version('2019-12-30')
                ->action('RecognizeDrivingLicense')
                ->method('POST')
                ->host('ocr.cn-shanghai.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-shanghai",
                        'Side' => $side,
                        'ImageURL' => $fileLoadAddress,
                    ],
                ])
                ->request();

            $card = $result->toArray();
            if ($side == 'face') {
                $response = [
                    'issue_date' => date('Y-m-d', strtotime($card['Data']['FaceResult']['IssueDate'] ?? '')),
                    'model' => $card['Data']['FaceResult']['Model'] ?? '',
                    'vehicle_type' => $card['Data']['FaceResult']['VehicleType'] ?? '',
                    'owner' => $card['Data']['FaceResult']['Owner'] ?? '',
                    'driver_name' => $card['Data']['FaceResult']['Owner'] ?? '',
                    'engine_number' => $card['Data']['FaceResult']['EngineNumber'] ?? '',
                    'plate_number' => $card['Data']['FaceResult']['PlateNumber'] ?? '',
                    'address' => $card['Data']['FaceResult']['Address'] ?? '',
                    'use_character' => $card['Data']['FaceResult']['UseCharacter'] ?? '',
                    'vin' => $card['Data']['FaceResult']['Vin'] ?? '',
                    'register_date' => date('Y-m-d', strtotime($card['Data']['FaceResult']['RegisterDate'] ?? '')),
                ];
            } else {

                [$inspectionTime, $annualReviewDate] = CarService::instance()->formatInspectionRecord($card['Data']['BackResult']['InspectionRecord'] ?? '');

                $response = [
                    'overall_dimension' => $card['Data']['BackResult']['OverallDimension'] ?? '',
                    'inspection_record' => $card['Data']['BackResult']['InspectionRecord'] ?? '',
                    'unladen_mass' => $card['Data']['BackResult']['UnladenMass'] ?? '',
                    'file_number' => $card['Data']['BackResult']['FileNumber'] ?? '',
                    'traction_mass' => $card['Data']['BackResult']['TractionMass'] ?? '',
                    'gross_mass' => $card['Data']['BackResult']['GrossMass'] ?? '',
                    'plate_number' => $card['Data']['BackResult']['PlateNumber'] ?? '',
                    'approved_passenger_capacity' => $card['Data']['BackResult']['ApprovedPassengerCapacity'] ?? '',
                    'energy_type' => $card['Data']['BackResult']['EnergyType'] ?? '',
                    'approved_load' => $card['Data']['BackResult']['ApprovedLoad'] ?? '',
                    'inspection_time' => $inspectionTime,
                    'annual_review_date' => $annualReviewDate,
                ];
            }

            return $response;
        } catch (\Exception $e) {
            return [];
        }
    }
}